package cn.hnh.service.Impl;

import cn.hnh.expection.OutofstockException;
import cn.hnh.expection.RepeatKillExpection;
import cn.hnh.mapper.GoodsMapper;
import cn.hnh.mapper.OrderMapper;
import cn.hnh.pojo.Goods;
import cn.hnh.pojo.Order;
import cn.hnh.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public int InsertGoods(Goods goods) {
        return goodsMapper.InsertGoods(goods);
    }

    @Override
    public Goods FindById(Integer id) {
        return goodsMapper.FindById(id);
    }

    @Override
    @Transactional
    public boolean ExecuteKill(Order order) throws RepeatKillExpection,OutofstockException{
        boolean res=true;
        try{
            if(orderMapper.InsertOrder(order)<=0){
                res=false;
                throw new RepeatKillExpection("重复秒杀!");
            }
            if(goodsMapper.UpdateStock(order.getGoodId())<=0){
                res=false;
                throw new OutofstockException("库存不足!");
            }
        }catch (RepeatKillExpection e){
            log.info("重复秒杀");
            throw e;
        }catch (OutofstockException e){
            log.info("库存不足");
            throw e;
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;
    }
}
